<?php

namespace app\cps\service;

use app\model\User;
use app\model\PayRecord;
use app\model\WatchPayRecord;
use app\model\Records;
use app\model\Videos;
use app\model\VideoDetails;
use app\model\OfficialAccounts;
use app\model\Link;
use think\facade\Db;
use app\model\UserRechargeConsumeAnalysis;
use app\model\ResponsibilityPerson;
use app\common\Error;

class UserService
{
    private $model;
    private $payRecordModel;
    private $watchPayRecordModel;
    private $recordsModel;
    private $videosModel;
    private $detailModel;
    private $officialAccountsModel;
    private $linkModel;
    private $userRechargeConsumeAnalysisModel;

    public function __construct(User $model, PayRecord $payRecordModel, WatchPayRecord $watchPayRecordModel, Records $recordsModel, Videos $videosModel, VideoDetails $detailModel, OfficialAccounts $officialAccountsModel, Link $linkModel, UserRechargeConsumeAnalysis $userRechargeConsumeAnalysisModel, ResponsibilityPerson $responsibilityPersonModel)
    {
        $this->model = $model;
        $this->payRecordModel = $payRecordModel;
        $this->watchPayRecordModel = $watchPayRecordModel;
        $this->recordsModel = $recordsModel;
        $this->videosModel = $videosModel;
        $this->detailModel = $detailModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->linkModel = $linkModel;
        $this->userRechargeConsumeAnalysisModel = $userRechargeConsumeAnalysisModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
    }

    // 获取用户列表数据
    public function getUserList($params, $userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];

        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }
        // 用户id
        if (!empty($params['id'])) {
            $where[] = ['id', '=', $params['id']];
        }

        // 链接id
        if (!empty($params['link_id'])) {
            $where[] = ['link_id', '=', $params['link_id']];
        }

        // 投放计划id
        if (!empty($params['advertiser_id'])) {
            $where[] = ['advertiser_id', '=', $params['advertiser_id']];
        }

        // 关注状态
        if (!empty($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        // 注册时间
        if (!empty($params['register_date'])) {
            $where[] = ['created_at', '>=', strtotime($params['register_date'])];
            $where[] = ['created_at', '<', strtotime($params['register_date'] . ' 23:59:59')];
        }

        // 关注时间
        if (!empty($params['follow_date'])) {
            $where[] = ['official_account_created_at', '>=', strtotime($params['follow_date'])];
            $where[] = ['official_account_created_at', '<', strtotime($params['follow_date'] . ' 23:59:59')];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, user_name, avatar, status, official_account_created_at, created_at, closing_time, mobile_system, link_id, activation_time, is_members, expiration_time, money, first_charge_date, last_login_time, advertiser_id');

        return $data;
    }

    // 查看用户详情
    public function getUserDetail($params, $userInfo)
    {
        $uid = $params['id'];
        // $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        // $responsibilityPersonId = $userInfo['cps_user_id'];
        // $responsibilityPersonName = $userInfo['cps_user_name'];

        $rechargeAmount = $this->payRecordModel->where(['uid' => $uid, 'status' => 1])->sum('total_fee');
        $rechargeNum = $this->payRecordModel->where(['uid' => $uid, 'status' => 1])->count();
        $consumeAmount = $this->watchPayRecordModel->where(['uid' => $uid])->sum('money');
        $lookNum = $this->recordsModel->where(['uid' => $uid])->group('video_id')->count();

        $userInfo = [
            'recharge_amount' => $rechargeAmount,
            'consume_amount' => $consumeAmount,
            'look_num' => $lookNum,
            'recharge_num' => $rechargeNum,
            // 'official_account_id' => $usedOfficialAccountId,
            // 'official_account_name' => $this->officialAccountsModel->getInfoById($usedOfficialAccountId, 'name')['name'],
            // 'responsibility_person_id' => $responsibilityPersonId,
            // 'responsibility_person_name' => $responsibilityPersonName
        ];

        return $userInfo;
    }

    // 获取用户充值/消费/观看数据
    public function getUserData($params)
    {
        $uid = $params['id'];
        $where = [
            ['uid', '=', $uid]
        ];
        $type = $params['type'] ?? 1;
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        if ($type == 1 && isset($params['status']) && is_numeric($params['status'])) {
            $where[] = ['status', '=', $params['status']];
        }

        if ($type == 1) {
            $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'order_no, wechat_order_no, type, total_fee, status, created_at, pay_time');
        } else if ($type == 2) {
            $data = $this->watchPayRecordModel->getPagingDataByWhere($where, $page, $limit, 'video_id, video_detail_id, money, created_at');

            if ($data['data']) {
                $data = self::getVideoData($data);
            }

        } else {
            $data = $this->recordsModel->getPagingDataByWhere($where, $page, $limit, 'video_id, video_detail_id, created_at');

            if ($data['data']) {
                $data = self::getVideoData($data);
            }
        }

        return $data;
    }

    // 获取短剧数据
    public function getVideoData($data)
    {
        $videoIds = array_column($data['data'], 'video_id');
        $detailIds = array_column($data['data'], 'video_detail_id');
        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name');
        $video = array_column($videoData, 'name', 'id');

        $detailData = $this->detailModel->getInfoByIds($detailIds, 'id, sort');
        $detail = array_column($detailData, 'sort', 'id');

        foreach ($data['data'] as $key => $value) {
            $data['data'][$key]['video_name'] = empty($video[$value['video_id']]) ? '' : $video[$value['video_id']];
            $data['data'][$key]['sort'] = empty($detail[$value['video_detail_id']]) ? '' : $detail[$value['video_detail_id']];
        }

        return $data;
    }

    // 获取用户统计数据
    public function getUserStatisticsData($userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        // 累计
        $where = [];
        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }
        $userData = $this->model->getBatchDataByWhere($where, 'activation_time, id');
        $totalUids = array_column($userData, 'id');

        // 今日
        $toDay = date('Ymd');
        // 昨日
        $yesterDay = date('Ymd', time() - 86400);
        // 本月
        $startDate = intval(date('Ym').'01');
        $endDate = intval(date('Ymd'));

        $toDayRegisterUids = $yesterDayRegisterUids = $totalUids = $thisMonthRegisterUids = [];
        $totalNum = 0;
        foreach ($userData as $key => $value) {
            $totalUids[] = $value['id'];
            $activationDate = date('Ymd', strtotime($value['activation_time']));
            if ($activationDate == $toDay) {
                // 今日
                $toDayRegisterUids[] = $value['id'];
            }
            if ($activationDate == $yesterDay) {
                // 昨日
                $yesterDayRegisterUids[] = $value['id'];
            }
            if ($startDate <= $activationDate && $activationDate <= $endDate) {
                // 本月
                $thisMonthRegisterUids[] = $value['id'];
            }
            $totalNum++;
        }

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $payRecord = $this->payRecordModel->getInfo([['link_id', 'in', $linkIds], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee, consume_date, activation_date');
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $payRecord = $this->payRecordModel->getInfo([['link_id', 'in', $linkIds], ['official_account_id', '=', $usedOfficialAccountId], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee, consume_date, activation_date');
        } else {
            $payRecord = $this->payRecordModel->getInfo([['official_account_id', '=', $usedOfficialAccountId], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee, consume_date, activation_date');
        }

        // 今日新增用户
        $toDayRegisterUids = array_unique($toDayRegisterUids);
        // 昨日新增用户
        $yesterDayRegisterUids = array_unique($yesterDayRegisterUids);
        // 本月新增用户
        $thisMonthRegisterUids = array_unique($thisMonthRegisterUids);

        $rechargeUserNum = $toDayRechargeNum = $yesterDayRechargeNum = $thisMonthRechargeNum = [];
        $totalPrice = $toDayPrice = $yesterDayPrice = $thisMonthPrice = 0;
        foreach ($payRecord as $key => $value) {
            // 累计
            $totalPrice += $value['total_fee'];
            $rechargeUserNum[] = $value['uid'];
            // 今日
            if (in_array($value['uid'], $toDayRegisterUids) && $value['activation_date'] == $toDay) {
                $toDayPrice += $value['total_fee'];
                $toDayRechargeNum[] = $value['uid'];
            }
            // 昨日
            if (in_array($value['uid'], $yesterDayRegisterUids) && $value['activation_date'] == $yesterDay) {
                $yesterDayPrice += $value['total_fee'];
                $yesterDayRechargeNum[] = $value['uid'];
            }
            // 本月
            if (in_array($value['uid'], $thisMonthRegisterUids)) {
                $thisMonthPrice += $value['total_fee'];
                $thisMonthRechargeNum[] = $value['uid'];
            }
        }

        $data = [
            'today_register_num' => count($toDayRegisterUids),
            'today_recharge_user_num' => count( array_unique($toDayRechargeNum) ),
            'today_recharge_amount' => round($toDayPrice, 2),

            'yesterday_register_num' => count($yesterDayRegisterUids),
            'yesterday_recharge_user_num' => count( array_unique($yesterDayRechargeNum) ),
            'yesterday_recharge_amount' => round($yesterDayPrice, 2),

            'this_month_register_num' => count($thisMonthRegisterUids),
            'this_month_recharge_user_num' => count( array_unique($thisMonthRechargeNum) ),
            'this_month_recharge_amount' => round($thisMonthPrice, 2),

            'total_register_num' => $totalNum,
            'total_recharge_user_num' => count( array_unique($rechargeUserNum) ),
            'total_recharge_amount' => round($totalPrice, 2),
        ];

        return $data;
    }

    // 定时器访问获取今日新增数据
    public function getUserToDayStatisticsData($userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        // 累计

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;

            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        }
        $where[] = ['register_date', '=', date('Ymd')];

        $userData = $this->model->getBatchDataByWhere($where, 'id,register_date');
        $toDayUids = array_unique(array_column($userData, 'id'));

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            $payRecord = $this->payRecordModel->getInfo([['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee');
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $payRecord = $this->payRecordModel->getInfo([['link_id', 'in', $linkIds], ['official_account_id', '=', $usedOfficialAccountId], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee');
        } else {
            $payRecord = $this->payRecordModel->getInfo([['official_account_id', '=', $usedOfficialAccountId], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee');
        }

        $toDayRechargeNum = [];
        $toDayPrice = 0;

        foreach ($payRecord as $key => $value) {
            // 今日
            if (in_array($value['uid'], $toDayUids)) {
                $toDayPrice = $toDayPrice + $value['total_fee'];
                $toDayRechargeNum[] = $value['uid'];
            }
        }

        $data = [
            'today_register_num' => count($toDayUids),
            'today_recharge_user_num' => count( array_unique($toDayRechargeNum) ),
            'today_recharge_amount' => round($toDayPrice, 2),
        ];

        return $data;
    }

    // 近10天用户数据统计
    public function getLastUserStatisticsData($redisUserInfo)
    {
        ini_set('memory_limit', '2048M');
        $usedOfficialAccountId = $redisUserInfo['cps_used_official_account_id'];

        $endDate = time();
        $startDate = time() - 9 * 86400;

        $date = $dates = [];
        for ($i = 9; $i >= 0; $i--) { 
            $date[] = date('Y-m-d', $startDate + $i * 86400);
            $dates[] = date('Ymd', $startDate + $i * 86400);
        }

        $where = [
            ['activation_time', '>=', $date[9] . ' 00:00:00'],
            ['activation_time', '<=', $date[0] . ' 23:59:59']
        ];

        $responsibilityPersonId = $redisUserInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($redisUserInfo['is_branch_office_manage']) && $redisUserInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $redisUserInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        } else if ($redisUserInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $responsibilityPersonId = $redisUserInfo['cps_user_id'];
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        } else {
            $where[] = ['official_account_id', '=', $usedOfficialAccountId];
        }
        $userData = $this->model->getBatchDataByWhere($where, 'id, activation_time, status');

        $result = $userInfo = $payRecord = $userFollowInfo = [];
        foreach ($userData as $key => $value) {
            $userInfo[date('Ymd', strtotime($value['activation_time']))][] = $value['id'];
        }

        if (!empty($redisUserInfo['is_branch_office_manage']) && $redisUserInfo['is_branch_office_manage'] == 1) {
            $payRecordData = $this->payRecordModel->getInfo([['consume_date', 'in', $dates], ['link_id', 'in', $linkIds], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee, consume_date, activation_date');
        } else if ($redisUserInfo['cps_user_name'] == config('enum.cps_user_name')) {
            $payRecordData = $this->payRecordModel->getInfo([['consume_date', 'in', $dates], ['official_account_id', '=', $usedOfficialAccountId], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee, consume_date, activation_date');
        } else {
            $payRecordData = $this->payRecordModel->getInfo([['consume_date', 'in', $dates], ['official_account_id', '=', $usedOfficialAccountId], ['link_id', 'in', $linkIds], ['status', '=', 1], ['total_fee', '>', 0]], 'uid, total_fee, consume_date, activation_date');
        }

        foreach ($payRecordData as $key => $value) {
            $payRecord[$value['consume_date']][] = $value;
        }

        foreach ($dates as $time) {

            $newUser = $rechargeNum = $rechargeUserNum = $rechargeAmount = 0;
            $activationUserRechargeNum = 0; // 激活用户充值笔数
            $activationUserRechargePeopleNum = 0; // 激活用户充值人数
            $activationUserRechargeAmount = 0; // 激活用户充值金额
            // 新增激活用户数
            if (!empty($userInfo[$time])) {
                $newUser = count($userInfo[$time]);
            }

            if (!empty($payRecord[$time])) {
                $uids = $activationUids = [];
                foreach ($payRecord[$time] as $value) {
                    if ($value['activation_date'] == $time) {
                        $activationUserRechargeNum += 1;
                        $activationUserRechargeAmount += $value['total_fee'];
                        $activationUids[] = $value['uid'];
                    }
                    $rechargeNum += 1;
                    $rechargeAmount += $value['total_fee'];
                    $uids[] = $value['uid'];
                }

                $rechargeUserNum = count(array_unique($uids));
                $activationUserRechargePeopleNum = count(array_unique($activationUids));
            }

            $result[] = [
                'date' => substr($time, 0, 4) . '-' . substr($time, 4, 2) . '-' . substr($time, 6, 2),
                'new_user' => $newUser,
                'activation_user_recharge_people_num' => $activationUserRechargePeopleNum,
                'activation_user_recharge_num' => $activationUserRechargeNum,
                'activation_user_recharge_amount' => round($activationUserRechargeAmount, 2),
                'recharge_user_num' => $rechargeUserNum,
                'recharge_num' => $rechargeNum,
                'recharge_amount' => round($rechargeAmount, 2)
            ];
        }

        return $result;
    }

    // 新增用户充值分析列表
    public function newUserRechargeAnalysisList($userInfo)
    {
        $usedOfficialAccountId = $userInfo['cps_used_official_account_id'];
        // 获取最近7天（不包含当天）该公众号注册的用户
        $startDate = time() - 6 * 86400;

        $dates = [];
        for ($i = 6; $i >= 0; $i--) { 
            $dates[] = date('Ymd', $startDate + $i * 86400);
            $activationDate[] = date('Y-m-d', $startDate + $i * 86400);
        }

        $where = [
            ['activation_time', '>=', $activationDate[6] . ' 00:00:00'],
            ['activation_time', '<=', $activationDate[0] . ' 23:59:59']
        ];
        $payWhere = [
            'consume_date' => $dates,
            'status' => 1,
        ];

        $responsibilityPersonId = $userInfo['cps_user_id'];
        $distributorInfo = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'is_distributor');

        if (!empty($userInfo['is_branch_office_manage']) && $userInfo['is_branch_office_manage'] == 1) {
            // 分公司
            $cpsUserId = $userInfo['cps_user_id'];
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $cpsUserId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $responsibilityPersonIds[] = $cpsUserId;
            $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $responsibilityPersonIds], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];

            $payWhere['link_id'] = $linkIds;
        } else if (!empty($distributorInfo['is_distributor'])) {
            // 分销商能查看他下面的投手的数据
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonId], 'id');
            $responsibilityPersonIds = array_column($responsibilityPersonData, 'id');
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonIds, 'link_switch' => 1], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];
            $payWhere['link_id'] = $linkIds;
        } else if ($userInfo['cps_user_name'] != config('enum.cps_user_name')) {
            $linkData = $this->linkModel->getDataByWhere(['official_account_id' => $usedOfficialAccountId, 'responsibility_person_id' => $responsibilityPersonId, 'link_switch' => 1], 'id');
            $linkIds = array_column($linkData, 'id');
            $where[] = ['link_id', 'in', $linkIds];

            $payWhere['link_id'] = $linkIds;
        }

        $data = $this->model->getBatchDataByWhere($where, "id, date_format(activation_time, '%Y%m%d') as activation_time");

        $userInfo = [];
        foreach ($data as $key => $value) {
            $userInfo[$value['activation_time']][] = $value['id'];
        }

        // 获取最近10天内激活的用户的最近5天（包含当天）充值数据
        $payRecord = $this->payRecordModel->getInfo($payWhere, 'uid, consume_date, total_fee, activation_date');
        $payRecordData = $payRecordResult = [];
        foreach ($payRecord as $key => $value) {
            $payRecordData[$value['uid']][] = $value['total_fee'];
            $payRecordResult[$value['activation_date']][] = $value;
        }

        // 组装数据
        foreach ($dates as $date) {

            $newUserNum = !empty($userInfo[$date]) ? count($userInfo[$date]) : 0;
            $rechargePeopleNum = 0; // 激活用户充值人数
            $totalRecharge = 0;
            $oneDayRecharge = $twoDayRecharge = $threeDayRecharge = $fourDayRecharge = $fiveDayRecharge = 0;

            if (!empty($payRecordResult[$date])) {
                $activationUids = [];
                foreach ($payRecordResult[$date] as $item) {

                    // if (!empty($payRecordData[$uid])) $totalAmount += array_sum($payRecordData[$uid]);
                    if ($item['consume_date'] == $date) {
                        $oneDayRecharge += $item['total_fee'];
                    } else if ($item['consume_date'] == date('Ymd', strtotime($date) + 86400)) {
                        $twoDayRecharge += $item['total_fee'];
                    } else if ($item['consume_date'] == date('Ymd', strtotime($date) + 2 * 86400)) {
                        $threeDayRecharge += $item['total_fee'];
                    } else if ($item['consume_date'] == date('Ymd', strtotime($date) + 3 * 86400)) {
                        $fourDayRecharge += $item['total_fee'];
                    } else if ($item['consume_date'] == date('Ymd', strtotime($date) + 4 * 86400)) {
                        $fiveDayRecharge += $item['total_fee'];
                    }
                    $activationUids[] = $item['uid'];
                    $rechargePeopleNum = count(array_unique($activationUids));

                }
                $totalRecharge = $oneDayRecharge + $twoDayRecharge + $threeDayRecharge + $fourDayRecharge + $fiveDayRecharge;
            }

            $result[] = [
                'date' => substr($date, 0, 4) . '-' . substr($date, 4, 2) . '-' . substr($date, 6, 2),
                'new_user_num'        => $newUserNum,
                'total_recharge'      => round($totalRecharge, 2),
                'recharge_people_num' => $rechargePeopleNum,
                'per_capita'          => empty($rechargePeopleNum) ? 0 : round($totalRecharge / $rechargePeopleNum, 2),
                'one_day_recharge'    => number_format($oneDayRecharge, 2),
                'two_day_recharge'    => number_format($twoDayRecharge, 2),
                'three_day_recharge'  => number_format($threeDayRecharge, 2),
                'four_day_recharge'   => number_format($fourDayRecharge, 2),
                'five_day_recharge'   => number_format($fiveDayRecharge, 2)
            ];
        }

        return $result;
    }

    // 用户分析
    // public function getUserAnalysisData($params)
    // {
    //     $page = $params['page'] ?? 1;
    //     $limit = $params['limit'] ?? 10;

    //     $data = $this->userRechargeConsumeAnalysisModel->getPagingDataByWhere([], $page, $limit, 'date, activation_user_num, recharge_money, consume_k_coins, account_balance, per_capita_recharge, per_capita_consume');
    //     return $data;
    // }

    // 修改密码
    public function chargePassWord($params, $userInfo)
    {
        try {
            $responsibilityPersonId = $userInfo['cps_user_id'];
            $responsibilityPersonName = $userInfo['cps_user_name'];

            if (empty($responsibilityPersonId) || empty($responsibilityPersonName)) {
                return ['message' => Error::PLEASE_REFRESH_THE_PAGE_AND_LOG_IN_AGAIN];
            }

            $data = $this->responsibilityPersonModel->getInfoById($responsibilityPersonId, 'id, password');

            if (empty($data)) {
                return ['message' => Error::NOT_REQUEST_AUTH_MESSAGE];
            }

            if (empty($params['original_password'])) {
                return ['message' => Error::ORIGINAL_PASSWORD_PARARATER_NOT_EXISTS];
            }

            $originalPassword = addslashes(strip_tags($params['original_password']));

            if (!password_verify($originalPassword, $data['password'])) {
                return ['message' => Error::ORIGINAL_PASSWORD_ERROR];
            }

            if (empty($params['password'])) {
                return ['message' => Error::PASSWORD_PARARATER_NOT_EXISTS];
            }

            if (empty($params['confirm_password'])) {
                return ['message' => Error::CONFIRM_PASSWORD_PARARATER_NOT_EXISTS];
            }

            $password = addslashes(strip_tags($params['password']));
            $confirmPassword = addslashes(strip_tags($params['confirm_password']));

            if ($password != $confirmPassword) {
                return ['message' => Error::TWO_DIFFERENT_PASSWORD_INPUTS];
            }

            $password = password_hash($params['password'], PASSWORD_DEFAULT);

            $id = $this->responsibilityPersonModel->edit(['id' => $responsibilityPersonId, 'password' => $password, 'updated_at' => time()]);

            return $id;
        } catch (\Exception $e) {
            return ['message' => $e->getMessage()];
        }
    }

    // 分销商用户列表
    public function getDistributionUserList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $info = $this->responsibilityPersonModel->getInfoByWhere(['token' => $params['token']], 'id');
        if (empty($info)) {
            return ['message' => Error::TOKEN_ERROR];
        }

        $pitcher = $this->responsibilityPersonModel->getDataByWhere(['pid' => $info['id']], 'id');
        $pitcherIds = array_column($pitcher, 'id');

        if (empty($pitcherIds)) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $linkData = $this->linkModel->getDataByWhere(['responsibility_person_id' => $pitcherIds], 'id,remark');
        $linkIds = array_column($linkData, 'id');

        if (empty($linkIds)) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $where[] = ['link_id', 'in', $linkIds];
        
        // 激活时间
        if (!empty($params['start_date'])) {
            $where[] = ['activation_time', '>=', $params['start_date']];
        }
        if (!empty($params['end_date'])) {
            $where[] = ['activation_time', '<=', $params['end_date']];
        }

        $data = $this->model->getPagingDataByWhere($where, $page, $limit, 'id, link_id, activation_time, ip, ua, open_id, clickid, advertiser_id');

        if($data['data']){

            // by huangxiaoshan add 2023-07-21
            $tmp_link_data = array_column($linkData,'remark','id');
            // end

            foreach ($data['data'] as $key=>$val) {
                $data['data'][$key]['remark'] = $tmp_link_data[$val['link_id']] ?? '';
            }
        }

        return $data;
    }
}